package com.pic.mgt.haishin;

import com.pic.mgt.controller.MessageUnitController;
import com.pic.mgt.executer.UnitDispatcher;
import com.pic.mgt.haishin.unit.HaishinMessage;
import com.pic.mgt.log.IgxLog;
import com.pic.mgt.manager.terminal.TerminalManager;
import com.pic.mgt.unit.Message;

public final class HaishinMessageUnitController extends MessageUnitController {
	private UnitDispatcher haishinMessageUnitDispatcher;
	private TerminalManager haishinTerminalManager;
	
	@Override
	protected String checkIsEffectiveTerminal(Message message) {
		HaishinMessage haishinMessageUnit = (HaishinMessage)message;
		
		// 判斷是否為有效的端末並回傳
		if (this.haishinTerminalManager.
				isEffectiveTerminalId(haishinMessageUnit.getTerminalId())) {
			return null;
		}
		else {
			return haishinMessageUnit.getTerminalId();
		}
	}
	
	@Override
	public void doMessageAction(Message message) {
		HaishinMessage haishinMessage = (HaishinMessage)message;
		
		// 判斷是否為有效的端末，若不是則寫warning log
		if (!this.haishinTerminalManager.
				isEffectiveTerminalId(haishinMessage.getTerminalId())) {
			// ********************** Log **********************
			if (IgxLog.messageLog.isWarnMode()) {
				IgxLog.messageLog.warn(this,
						"An Ineffective terminal '{}' uploaded a transaction message '{}'.",
						haishinMessage.getTerminalId(), message.getUnitName());
			}
			// ********************** Log **********************
		}
		
		// 直接交給 UnitDispatcher 做執行
		this.haishinMessageUnitDispatcher
						.sendToUnitExecuter(message);
	}
	
	// --- getter and setter ---
	
	public void setHaishinMessageUnitDispatcher(
			UnitDispatcher haishinMessageUnitDispatcher) {
		this.haishinMessageUnitDispatcher = haishinMessageUnitDispatcher;
	}

	public void setHaishinTerminalManager(TerminalManager haishinTerminalManager) {
		this.haishinTerminalManager = haishinTerminalManager;
	}

}
